<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h3>医嘱详情</h3>
          <div class="header-actions">
            <el-button 
              type="primary" 
              v-if="medicalOrderData.status === '已开立'"
              @click="handleEdit"
              v-permission="'medical_order:update'"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              v-if="medicalOrderData.status === '已开立'"
              @click="handleExecute"
              v-permission="'medical_order:execute'"
            >
              开始执行
            </el-button>
            <el-button 
              type="warning" 
              v-if="medicalOrderData.status === '执行中'"
              @click="handleComplete"
              v-permission="'medical_order:execute'"
            >
              完成执行
            </el-button>
            <el-button 
              type="danger" 
              v-if="medicalOrderData.status !== '已停止' && medicalOrderData.status !== '已执行'"
              @click="handleStop"
              v-permission="'medical_order:update'"
            >
              停止医嘱
            </el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="medicalOrderData.id">
        <el-descriptions title="医嘱信息" :column="3" border>
          <el-descriptions-item label="医嘱编号">{{ medicalOrderData.orderId }}</el-descriptions-item>
          <el-descriptions-item label="医嘱类型">{{ medicalOrderData.type }}</el-descriptions-item>
          <el-descriptions-item label="医嘱状态">
            <el-tag :type="getStatusType(medicalOrderData.status)">{{ medicalOrderData.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityType(medicalOrderData.priority)" size="small">
              {{ medicalOrderData.priority }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下达时间">{{ formatDate(medicalOrderData.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(medicalOrderData.updatedAt) }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-descriptions title="患者信息" :column="3" border>
          <el-descriptions-item label="姓名">
            <el-button type="text" @click="viewPatient(medicalOrderData.patientId)">
              {{ medicalOrderData.patientInfo?.name }}
            </el-button>
          </el-descriptions-item>
          <el-descriptions-item label="性别">{{ medicalOrderData.patientInfo?.gender }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ medicalOrderData.patientInfo?.age || '-' }}</el-descriptions-item>
          <el-descriptions-item label="患者ID">{{ medicalOrderData.patientInfo?.patientId }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-descriptions title="医生信息" :column="3" border>
          <el-descriptions-item label="姓名">{{ medicalOrderData.doctorInfo?.name }}</el-descriptions-item>
          <el-descriptions-item label="工号">{{ medicalOrderData.doctorInfo?.staffId }}</el-descriptions-item>
          <el-descriptions-item label="职称">{{ medicalOrderData.doctorInfo?.title }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-card class="content-card">
          <template #header>
            <div class="section-header">
              <h4>医嘱内容</h4>
            </div>
          </template>
          
          <div v-for="(item, index) in medicalOrderData.items" :key="index" class="order-item-container">
            <div class="order-item-header">
              <el-tag size="small" :type="getItemType(item.type)">{{ item.type }}</el-tag>
              <span class="order-item-content">{{ item.content }}</span>
            </div>
            <div class="order-item-details">
              <span v-if="item.frequency" class="detail-item">
                <label>执行频次：</label>{{ item.frequency }}
              </span>
              <span v-if="item.duration" class="detail-item">
                <label>持续时间：</label>{{ item.duration }}
              </span>
              <div v-if="item.note" class="detail-note">
                <label>备注：</label>{{ item.note }}
              </div>
            </div>
          </div>
          
          <div v-if="medicalOrderData.note" class="order-note">
            <label>医嘱说明：</label>
            <div class="note-content">{{ medicalOrderData.note }}</div>
          </div>
        </el-card>
        
        <el-divider />
        
        <el-card class="execution-card">
          <template #header>
            <div class="section-header">
              <h4>执行记录</h4>
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item
              timestamp="医嘱开立"
              :type="getTimelineType('开立')"
            >
              <h4>医嘱开立</h4>
              <p>开立时间：{{ formatDate(medicalOrderData.createdAt) }}</p>
              <p>开立医生：{{ medicalOrderData.doctorInfo?.name }}</p>
            </el-timeline-item>
            
            <el-timeline-item
              v-if="medicalOrderData.execution"
              timestamp="开始执行"
              :type="getTimelineType('执行')"
            >
              <h4>开始执行</h4>
              <p>执行时间：{{ formatDate(medicalOrderData.execution.executedAt) }}</p>
              <p>执行人员：{{ medicalOrderData.execution.executedByInfo?.name }}</p>
              <p v-if="medicalOrderData.execution.note">备注：{{ medicalOrderData.execution.note }}</p>
            </el-timeline-item>
            
            <el-timeline-item
              v-if="medicalOrderData.stop"
              timestamp="医嘱停止"
              :type="getTimelineType('停止')"
            >
              <h4>医嘱停止</h4>
              <p>停止时间：{{ formatDate(medicalOrderData.stop.stoppedAt) }}</p>
              <p v-if="medicalOrderData.stop.reason">停止原因：{{ medicalOrderData.stop.reason }}</p>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { medicalOrderAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'

// 路由相关
const route = useRoute()
const router = useRouter()
const orderId = ref(route.params.id)

// 数据加载状态
const loading = ref(false)

// 医嘱数据
const medicalOrderData = ref({})

// 获取医嘱详情
const getMedicalOrderDetail = async () => {
  loading.value = true
  try {
    const res = await medicalOrderAPI.getMedicalOrder(orderId.value)
    medicalOrderData.value = res.data
  } catch (error) {
    console.error('获取医嘱详情失败', error)
    ElMessage.error('获取医嘱详情失败')
  } finally {
    loading.value = false
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '已开立':
      return 'warning'
    case '执行中':
      return 'primary'
    case '已执行':
      return 'success'
    case '已停止':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取优先级标签类型
const getPriorityType = (priority) => {
  switch (priority) {
    case '急诊':
      return 'danger'
    case '加急':
      return 'warning'
    case '常规':
      return 'info'
    default:
      return ''
  }
}

// 获取医嘱项目类型标签
const getItemType = (type) => {
  switch (type) {
    case '药品':
      return 'success'
    case '检查':
      return 'warning'
    case '检验':
      return 'info'
    case '手术':
      return 'danger'
    default:
      return ''
  }
}

// 获取时间线类型
const getTimelineType = (action) => {
  switch (action) {
    case '开立':
      return 'primary'
    case '执行':
      return 'success'
    case '停止':
      return 'danger'
    default:
      return 'info'
  }
}

// 查看患者
const viewPatient = (patientId) => {
  router.push(`/patients/detail/${patientId}`)
}

// 返回列表页
const goBack = () => {
  router.push('/medical-orders/list')
}

// 编辑医嘱
const handleEdit = () => {
  router.push(`/medical-orders/edit/${orderId.value}`)
}

// 开始执行医嘱
const handleExecute = () => {
  ElMessageBox.confirm('确认开始执行该医嘱？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await medicalOrderAPI.executeMedicalOrder(orderId.value, {
        executorId: localStorage.getItem('userId'),
        executorName: localStorage.getItem('userName'),
        executeTime: new Date()
      })
      ElMessage.success('医嘱已开始执行')
      getMedicalOrderDetail()
    } catch (error) {
      console.error('执行医嘱失败', error)
      ElMessage.error(error.message || '执行医嘱失败')
    }
  }).catch(() => {})
}

// 完成执行医嘱
const handleComplete = () => {
  ElMessageBox.confirm('确认该医嘱已完成执行？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await medicalOrderAPI.updateMedicalOrder(orderId.value, { 
        status: '已执行',
        completionInfo: {
          completerId: localStorage.getItem('userId'),
          completerName: localStorage.getItem('userName'),
          completeTime: new Date()
        }
      })
      ElMessage.success('医嘱已完成执行')
      getMedicalOrderDetail()
    } catch (error) {
      console.error('更新医嘱状态失败', error)
      ElMessage.error(error.message || '更新医嘱状态失败')
    }
  }).catch(() => {})
}

// 停止医嘱
const handleStop = () => {
  ElMessageBox.prompt('请输入停止原因', '停止医嘱', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '停止原因不能为空',
    type: 'warning'
  }).then(async ({ value }) => {
    try {
      await medicalOrderAPI.stopMedicalOrder(orderId.value, {
        reason: value,
        stopperId: localStorage.getItem('userId'),
        stopperName: localStorage.getItem('userName'),
        stopTime: new Date()
      })
      ElMessage.success('医嘱已停止')
      getMedicalOrderDetail()
    } catch (error) {
      console.error('停止医嘱失败', error)
      ElMessage.error(error.message || '停止医嘱失败')
    }
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  getMedicalOrderDetail()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.content-card {
  margin: 20px 0;
}

.section-header {
  margin-bottom: 20px;
}

.order-item-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
}

.order-item-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.order-item-content {
  margin-left: 10px;
  font-weight: bold;
}

.order-item-details {
  padding-left: 35px;
  color: #666;
}

.detail-item {
  margin-right: 20px;
}

.detail-item label,
.detail-note label {
  color: #909399;
  margin-right: 5px;
}

.detail-note {
  margin-top: 5px;
}

.order-note {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.note-content {
  margin-top: 5px;
  color: #666;
}

.execution-card {
  margin-top: 20px;
}
</style> 